$(document).ready(function () {
  $("body").append('<div id="main-container" class="container"></div>');
  $("#main-container").append(
    '<div  id="client_credentials" class="sub-block"><h2>client_credentials申请令牌</h2></div>'
  );
  $("#client_credentials").append('<p class="token-content-json"></p>');
  $("#client_credentials").append(
    '<div class="btn-container"><button id="client_credentials_btn">申请令牌client_credentials</button></div>'
  );

  $("#main-container").append(
    '<div id="authorization_code" class="sub-block" ><h2>授权码模式需要先拿到授权码再申请令牌</h2></div>'
  );
  $("#authorization_code").append(
    '<input id="authorization_code_content"  placeholder="请输入授权码"/>'
  );
  $("#authorization_code").append('<p class="token-content-json"></p>');
  $("#authorization_code").append(
    '<div class="btn-container"><button id="authorization_code_btn">申请令牌authorization_code</button></div>'
  );

  $("#main-container").append(
    '<div id="opaque" class="sub-block" ><h2>opaque</h2></div>'
  );
  $("#opaque").append('<p class="token-content-json"></p>');
  $("#opaque").append('<p class="token-content-json"></p>');
  $("#opaque").append(
    '<div class="btn-container"><button id="opaque_btn">opaque 申请令牌</button><button id="opaque_btn_validate">opaque 验证令牌</button></div>'
  );

  $("#main-container").append(
    '<div id="resource_server" class="sub-block"><h2>测试：携带touken访问resource_server demo端点</h2></div>'
  );
  $("#resource_server").append('<input type=text class="token-content-json" placeholder="token" />');
  $("#resource_server").append('<p class="token-content-json"></p>');
  $("#resource_server").append('<div class="btn-container"><button id="resource_server_token_btn">申请令牌resource_server_token</button><button id="resource_server_btn">测试资源服务器demo端点</button></div>');

  $(".container")
    .css("display", "flex")
    .css("flex-direction", "column")
    .css("padding", "0 20px");
  $(".sub-block")
    .css("border", "1px solid gray")
    .css("position", "relative")
    .css("margin-top", "8px")
    .css("min-height", "200px")
    .css("display", "flex")
    .css("flex-direction", "column")
    .css("padding", "0 0 30px 0");
  $(".btn-container")
    .css("position", "absolute")
    .css("bottom", "2px")
    .css("right", "20px")
    .css("float", "right");
  $("button").css("margin-left","10px")
  $("h2").css("margin", "0 0 10px 0").css("padding", "0");
  $(".token-content-json")
    .css("border", "1px solid blue")
    .css("min-height", "100px")
    .css("word-break", "break-all");
  $(".token-content-json-result")
    .css("border", "1px solid blue")
    .css("min-height", "100px")
    .css("word-break", "break-all");

  $("#authorization_code_content").css("height", "40px");

  $("#client_credentials_btn").click(function () {
    var formData = new FormData();
    formData.append("grant_type", "client_credentials");
    $.ajax({
      url: "/oauth2/token", // OAuth2ClientAuthenticationFilter
      type: "POST",
      cache: false,
      contentType: false, // 重要：不要在这里设置contentType
      processData: false,
      data: formData,
      beforeSend: function (xhr) {
        // jquery中不要写content-type会自动处理
        xhr.setRequestHeader(
          "Authorization",
          "Basic " + btoa("resource_server:resource_server_secret")
        );
      },
      success: function (response) {
        console.log("client_credentials_btn:", response);
        // 将 JavaScript 对象转换为格式化后的 JSON 字符串
        // console.log(response.access_token)
        var formattedJsonString = JSON.stringify(response, null, 2);
        $("#client_credentials > .token-content-json").text(
          formattedJsonString
        );
      },
      error: function (xhr, status, error) {
        console.error("Error:", error);
      },
    });
  });
  $("#opaque_btn").click(function () {
    var formData = new FormData();
    formData.append("grant_type", "client_credentials");
    formData.append("scope", "CUSTOM");
    $.ajax({
      url: "/oauth2/token",
      type: "POST",
      cache: false,
      contentType: false, // 重要：不要在这里设置contentType
      processData: false,
      data: formData,
      beforeSend: function (xhr) {
        // jquery中不要写content-type会自动处理
        xhr.setRequestHeader(
          "Authorization",
          "Basic " + btoa("opaque-client:opaque-secret")
        );
      },
      success: function (response) {
        console.log("opaque_btn:", response);
        // 将 JavaScript 对象转换为格式化后的 JSON 字符串
        // console.log(response.access_token)
        var formattedJsonString = JSON.stringify(response, null, 2);
        $("#opaque > .token-content-json").first().text(formattedJsonString);
      },
      error: function (xhr, status, error) {
        console.error("Error:", error);
      },
    });
  });
  //            curl -X POST 'http://localhost:8080/oauth2/introspect?token=iED8-…' \
  //            --header 'Authorization: Basic Y2xpZW50OnNlY3JldA=='
  $("#opaque_btn_validate").click(function () {
    var token = $.parseJSON(
      $("#opaque > .token-content-json").first().text()
    ).access_token;
    if (!token) {
      throw new Error("token is null!");
    }
    var formData = new FormData();
    formData.append("token", token);
    $.ajax({
      url: "oauth2/introspect",
      type: "POST",
      cache: false,
      contentType: false, // 重要：不要在这里设置contentType
      processData: false,
      data: formData,
      beforeSend: function (xhr) {
        // jquery中不要写content-type会自动处理
        xhr.setRequestHeader(
          "Authorization",
          "Basic " + btoa("opaque-client:opaque-secret")
        );
      },
      success: function (response) {
        console.log("opaque_btn_validate:", response);
        // 将 JavaScript 对象转换为格式化后的 JSON 字符串
        // console.log(response.access_token)
        var formattedJsonString = JSON.stringify(response, null, 2);
        //$("#opaque > .token-content-json").last().css('background-color','green');
        $("#opaque > .token-content-json").last().text(formattedJsonString);
      },
      error: function (xhr, status, error) {
        console.error("Error:", error);
      },
    });
  });
  $("#authorization_code_btn").click(function () {
    var formData = new FormData();
    formData.append("grant_type", "authorization_code");
    formData.append(
      "redirect_uri",
      "http://localhost:8082/login/oauth2/code/my_authorization_server"
    );
    var authorization_code_val = $("#authorization_code_content").val();
    if (!authorization_code_val) {
      throw new Error("authorization_code is null!");
    }
    console.log(authorization_code_val);
    formData.append("code", authorization_code_val);
    formData.append(
      "code_verifier",
      "z1W46zuLHiQbb3fu77xz7ZPWiFAn3cl6GHC70SYZwgY"
    );
    $.ajax({
      url: "/oauth2/token",
      //url: "/client-form-submit",
      type: "POST",
      cache: false,
      contentType: false, // 重要：不要在这里设置contentType
      processData: false,
      data: formData,
      beforeSend: function (xhr) {
        // jquery中不要写content-type会自动处理
        xhr.setRequestHeader(
          "Authorization",
          "Basic " + btoa("code-client:code-secret")
        );
      },
      success: function (response) {
        console.log("authorization_code_btn:", response);
        // 将 JavaScript 对象转换为格式化后的 JSON 字符串
        console.log(response.access_token);
        var formattedJsonString = JSON.stringify(response, null, 2);
        $("#authorization_code > .token-content-json").text(
          formattedJsonString
        );
      },
      error: function (xhr, status, error) {
        console.error("Error:", error);
      },
    });
  });
  $("#resource_server_btn").click(function () {
    var tokenStr = $("#resource_server > .token-content-json").first().val();
    var tokenObj=JSON.parse(tokenStr);
    var token = tokenObj.access_token;
    if (token.length>128){
        console.log("jwt token===",token)
    } else {
        console.log("opaque token===",token)
    }

    if (!token) {
      throw new Error("token is null!");
    }
    $.ajax({
      url: "http://localhost:8083/demo",
      type: "GET",
      cache: false,
      contentType: false, // 重要：不要在这里设置contentType
      processData: false,
      beforeSend: function (xhr) {
        // curl 'http://localhost:8083/demo' \
        //   --header 'Authorization: Bearer 2zLyYA8b6Q54-…'
        xhr.setRequestHeader("Authorization", "Bearer " + token);
        if (token.length>128) {
            xhr.setRequestHeader(
              "type",
              "jwt"
            );
        }
      },
      success: function (response) {
        console.log("resource_server_btn:", response);
        // 将 JavaScript 对象转换为格式化后的 JSON 字符串
        var formattedJsonString = JSON.stringify(response, null, 2);
        $("#resource_server > .token-content-json")
          .last()
          .text(formattedJsonString);
      },
      error: function (xhr, status, error) {
        console.error("Error:", error);
      },
    });
  });
  $("#resource_server_token_btn").click(function () {
    var formData = new FormData();
    formData.append("grant_type", "client_credentials");
    $.ajax({
      url: "/oauth2/token",
      //url: "/client-form-submit",
      type: "POST",
      cache: false,
      contentType: false, // 重要：不要在这里设置contentType
      processData: false,
      data:formData,
      beforeSend: function (xhr) {
         // jquery中不要写content-type会自动处理
        xhr.setRequestHeader(
          "Authorization",
          "Basic " + btoa("opaque-client:opaque-secret")
        );
      },
      success: function (response) {
        console.log("resource_server_btn:", response);
        // 将 JavaScript 对象转换为格式化后的 JSON 字符串
        var formattedJsonString = JSON.stringify(response, null, 2);
        $("#resource_server > .token-content-json")
          .first()
          .val(formattedJsonString);
      },
      error: function (xhr, status, error) {
        console.error("Error:", error);
      },
    });
  });
});
